(function($){
Drupal.wordgame = Drupal.wordgame || {};
Drupal.behaviors.wordgame = {
  attach: function(context, settings) {
    $('.letter-cell:not(.wordgame-processed)').addClass('wordgame-processed')
      .each(function(index, item) {
        $(item).hover(function(e) {
          var id = $(item).attr('class').match(/\bword-(\S+)\b/)[1];
          $('.word-' + id).addClass('hover');
        }, function(e){
          var id = $(item).attr('class').match(/\bword-(\S+)\b/)[1];
          $('.word-' + id).removeClass('hover');
        });
      });
    $('.letter-guest').click(function(e) {
      var itemClass = '', col = 0, row = 0;
      itemClass = $(this).attr('class');
      // Determine the block module and delta.
      col = itemClass.match(/\bcol-(\S+)\b/)[1];
      row = itemClass.match(/\brow-(\S+)\b/)[1];
      Drupal.wordgame.position = {'col': col, 'row': row};
      $('#wordgame-letters').dialog();//css('top', e.pageY - 30).css('left', e.pageX).show();
    });
    $('#wordgame-letters:not(.wordgame-processed)').addClass('wordgame-processed')
      .find('.letter').click(function() {
        var itemClass = '', char = '';
        itemClass = $(this).attr('class');
        char = itemClass.match(/\bletter-(\S+)\b/)[1];
        $.get('/wordgame/guest',{
          'position' : Drupal.wordgame.position,
          'char': char
        }, function(message){
          Drupal.wordgame.wordgameUpdateBoard(message.data);
        });
        $('#wordgame-letters').dialog('close');
      });
  }
}

/**
 * We depend on the Nodejs module successfully create a socket for us.
 */
Drupal.Nodejs.connectionSetupHandlers.wordgame = {
  connect: function () {
    for (var wgid in Drupal.settings.wordgame.games) {
    }
    Drupal.wordgame.initialised = true;
  }
};

Drupal.Nodejs.callbacks.wordgameUpdateBoard = {
  callback: function (message) {
    Drupal.wordgame.wordgameUpdateBoard(message.data);
  }
};


Drupal.wordgame.wordgameUpdateBoard = function(message) {
  if (message.result == true) {
    var id = '#cell-' + message.row + "-" + message.col;
    $(id).removeClass('letter-guest').addClass('letter-visible').html(message.char);
    $(".letter-" + message.char).find('.amounts').html(message.amount);
    if (message.amount == '') {
      $(".letter-" + message.char).hide();
    }
    $(".total-points").html(message.point);
    if (message.finished == true) {
      $('<div title="' + Drupal.t('Notice') + '">Congratulations on your victory!</div>').dialog(
        {
          buttons: {
            'Next': function() {
              window.location.reload();
            }
          },
          close: function() {
            window.location.reload();
          }
        }
      );
    }
  }
  else {
    $('<div>Wrong! Please try again.</div>').dialog();
  }
}
})(jQuery);